package org.micode.demo.web.controller;

import org.micode.common.helper.I18nMsgHelper;
import org.micode.common.utils.StringExtUtils;
import org.micode.demo.web.base.BaseWebAdminController;
import org.micode.demo.web.config.WebAdminConfig;
import org.micode.common.annotation.NoNeedLogin;
import org.micode.common.annotation.SysLog;
import org.micode.common.domain.ApiResult;
import org.micode.common.domain.vo.KeyVO;
import org.micode.common.enums.OperationModeEnum;
import org.micode.common.enums.ResultEnum;
import org.micode.libs.dao.vo.ImageCodeVO;
import org.micode.demo.biz.vo.SysUserVO;
import org.micode.demo.db.cache.user.SysUserCache;
import org.micode.demo.web.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/web-admin/login")
public class LoginController extends BaseWebAdminController {

    @Autowired
    private LoginService loginService;

    /**
     * 验证码生成
     */
    @NoNeedLogin
    @PostMapping("/getImageCode")
    public ApiResult<ImageCodeVO> getImageCode(
            @RequestBody @Validated KeyVO<String> codeKey) {
        log.debug(I18nMsgHelper.get("api.call.login.getImageCode") + "(codeKey: {})", codeKey.getKey());
        ImageCodeVO imageCode = new ImageCodeVO();
        imageCode.setUuid(codeKey.getKey());
        imageCode.setLoginApp(WebAdminConfig.SERVICE_NAME);
        return invokeMethod(loginService::getImageCode, imageCode);
    }

    private void fillUserVO(SysUserVO user) {
        user.setToken(getToken());
        if (StringExtUtils.isAllEmpty(user.getLoginApp())) {
            user.setLoginApp(WebAdminConfig.SERVICE_NAME);
        }
        user.setLoginIp(this.getLoginClientIp());
    }

    @Profile("dev")  // 标记为只有dev环境有效，在其他环境下这个loginForTest是无效的
    @SysLog(value="{api.syslog.login.loginForTest}", operationMode= OperationModeEnum.NORMAL)
    @NoNeedLogin
    @PostMapping("/loginForTest")
    public ApiResult<SysUserCache> loginForTest(
            @RequestBody @Validated KeyVO<Long> userKey ) {
        log.debug(I18nMsgHelper.get("api.call.login.loginForTest") + "(userKey: {})", userKey.getKey());
        SysUserVO userVO = new SysUserVO();
        userVO.setUserId(userKey.getKey());
        fillUserVO(userVO);
        return invokeMethod(loginService::loginForTest, userVO);
    }

    /**
     * 通过账号和密码登录。
     * 必要的输入字段是:
     * customerName
     * agentName
     * agentPwd
     * phoneNumber
     *
     * @param sysUser 登录用户的信息
     * @return 登录成功后的结果信息
     */
    @SysLog(value = "{api.syslog.login.loginByAccount}", operationMode = OperationModeEnum.NORMAL)
    @NoNeedLogin
    @PostMapping("/loginByAccount")
    public ApiResult<SysUserCache> loginByAccount(
            @RequestBody SysUserVO sysUser) {
        log.debug(I18nMsgHelper.get("api.call.login.loginByAccount") + ": {}", sysUser);
        fillUserVO(sysUser);
        return invokeMethod(loginService::loginByAccount, sysUser);
    }

    @PostMapping("/logout")
    public ApiResult<Boolean> logout() {
        log.debug(I18nMsgHelper.get("api.call.login.logout") + "({})", currentUserId());
        return invokeMethod(this::logoutInner,
                ResultEnum.SUCCESS, I18nMsgHelper.get("api.except.login.logout"));
    }

    private Boolean logoutInner() {
        String token = getToken();
        if (!StringUtils.isEmpty(token)) {
            return loginService.userLogout(token, getLoginClientIp());
        }
        return Boolean.TRUE;
    }

}
